package com.qingfeng.client.api;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.qingfeng.client.bean.Seller;
import com.qingfeng.client.dao.SellerMapper;
import com.qingfeng.client.service.SellerService;
import com.qingfeng.client.util.MD5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


@Controller
@ResponseBody
@RequestMapping("/auth")
@SessionAttributes("auth")
public class Auth extends BaseV1Api{

    Logger logger = LoggerFactory.getLogger(this.getClass().getName());


    //    private int expiry = 3600 * 24 * 30 * 12 * 50;
    @Resource
    private SellerService sellerService;

    @Resource
    private SellerMapper sellerDao;


    @RequestMapping(value = "/notLogin")
    public String notLogin() {
        return "0xff";
    }

    @RequestMapping(value = "/api/login")
    public Object login(@RequestBody Seller sellerBean, HttpServletRequest request) {
        String msg = StringUtils.EMPTY;
        boolean haveStore = false;
        Seller user = sellerService.login(sellerBean.getName(), sellerBean.getPassword(), sellerBean.getCountryPhoneCode());
        if (user != null) {
            request.getSession().setAttribute("auth", user);
            if (user.getStoreId() != null) {
                haveStore = true;
            }
        } else {
            msg = "用户名或密码错误";
        }
        if (StringUtils.isEmpty(msg)) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("result", 1);
            jsonObject.put("haveStore", haveStore);
            return jsonObject;
        } else {
            return error(msg);
        }
    }

    /**
     * 注销session
     * @return
     */
    @RequestMapping(value = "/api/logout")
    public Object logoug(SessionStatus sessionStatus) {
        sessionStatus.setComplete();
        return success(null);
    }

    @RequestMapping(value = "/app/login")
    public Object appLogin(@RequestBody Seller sellerBean, HttpServletRequest request) {
        boolean haveStore = false;
        Seller user = sellerService.login(sellerBean.getName(), sellerBean.getPassword(), sellerBean.getCountryPhoneCode());
        if (user == null) {
            return error("用户名、密码错误");
        }

        String key = user.getName() + user.getPassword() + System.currentTimeMillis() + (int) (Math.random() * 100);
        String token = MD5Util.get(key);//编码
        user.setToken(token);
        if (sellerDao.updateById(user)>0) {
            return error("更新token失败");
        }

        request.getSession().setAttribute("auth", user);
        if (user.getStoreId() != null) {
            haveStore = true;
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", 1);
        jsonObject.put("haveStore", haveStore);
        jsonObject.put("token", user.getToken()); //用于存放在http请求的head中
        return jsonObject;
    }

    /**
     * 手机注册
     *
     * @param sellerBean
     * @param session
     * @return
     */
    @RequestMapping(value = "/api/register")
    public Object register(@RequestBody Seller sellerBean, HttpSession session) {
        String msg = StringUtils.EMPTY;
        Integer id = sellerService.register(sellerBean);

        session.setAttribute("auth", sellerBean);
        if (StringUtils.isEmpty(msg)) {
            return success(null);
        } else {
            return error(msg);
        }
    }

    /**
     * 发送重置密码验证码
     *
     * @param phone
     * @param session
     * @return
     */
    @RequestMapping(value = "/app/resetMsg")
    public Object resetMsg(String phone, HttpSession session) {
        boolean result = true;
//      String code = MsgTool.createRandom(true, 6);
//      result = MsgTool.resetPassword(phone,code);
        String code = "6666";
        session.setAttribute("code", code);
        session.setAttribute("phone", phone);
        return returnBoolean(result);
    }



    @RequestMapping(value = "/app/updatePassword")
    public Object updatePassword(String oldPassword, String newPassword, HttpSession session){
        Seller user = getUser();
        if (StringUtils.isEmpty(newPassword)){
            return error("新密码不能为空");
        }
        boolean result = false;
        if (user.getPassword().equals(oldPassword)) {
            user.setPassword(newPassword);
            int flag = sellerDao.updateById(user);
            if (flag>0){
                user=null;
                return success("更新成功");
            }
        }else {
            return error("原密码错误");
        }
        return returnBoolean(result);
    }

}
